package com.njzdr.common;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;

import androidx.appcompat.app.AlertDialog;

import com.coszero.utilslibrary.utils.LogX;
import com.coszero.utilslibrary.utils.ToastUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * Desc： 蓝牙开发工具类
 *
 * @author xmqian
 * Email:xmqian93@163.com
 * Date: 2020/10/27 0027 17:56
 */
public class BluetoothUtils {
    private static final String TAG = "bluetooth";
    /**
     * 开启蓝牙请求码,如果需要开启回调可以使用此值在
     * onActivityResult()方法中捕捉
     */
    public static final int REQUEST_ENABLE_BT = 222;
    private BluetoothAdapter mAdapter;

    private boolean isConnection = false;

    private static BluetoothUtils instance;

    public static BluetoothUtils getInstance() {
        if (instance == null) {
            instance = new BluetoothUtils();
        }
        return instance;
    }

    /**
     * @return 返回蓝牙适配器
     */
    public BluetoothAdapter getmAdapter() {
        return mAdapter = BluetoothAdapter.getDefaultAdapter();
    }

    /**
     * 检查蓝牙
     * 判断蓝牙是否打开
     * 判断是否支持蓝牙
     */
    public boolean checkBluetooth(Activity activity) {
        mAdapter = BluetoothAdapter.getDefaultAdapter();
        //为null说明设备不支持蓝牙
        if (null != mAdapter) {
            //尝试打开蓝牙
            if (!mAdapter.isEnabled()) {
                LogX.i(TAG, "蓝牙未开启,正在开启蓝牙");
                openBluetooth(activity);
            }
            return true;
        }
        LogX.e(TAG, "设备不支持蓝牙");
        return false;
    }


    /**
     * 获取已配对的蓝牙列表
     *
     * @return Set<BluetoothDevice>
     */
    public Set<BluetoothDevice> getAlreadyPairedBluetoothDeviceList() {
        Set<BluetoothDevice> devices = null;
        if (mAdapter != null) {
            devices = mAdapter.getBondedDevices();
            if (devices.size() > 0) {
                for (Iterator<BluetoothDevice> it = devices.iterator(); it.hasNext(); ) {
                    BluetoothDevice device = it.next();
                    LogX.e(TAG, device.getName() + " " + device.getAddress());
                }
            } else {
                LogX.e(TAG, "没有已配对的蓝牙设备");
            }
        }
        return devices;
    }

    /**
     * 得到已经配对的列表
     *
     * @return
     */
    public List<BluetoothDevice> getPairList() {
        Set<BluetoothDevice> mSet = getmAdapter().getBondedDevices();
        final Iterator mIterator = mSet.iterator();
        List<BluetoothDevice> list = new ArrayList<>();
        while (mIterator.hasNext()) {
            BluetoothDevice bluetoothDevice = (BluetoothDevice) mIterator.next();
            list.add(bluetoothDevice);
        }
        return list;
    }


    /**
     * 打开蓝牙
     * @param activity activity,如果需要开启回调,可在activity中使用onRe
     */
    public void openBluetooth(Activity activity) {
        if (mAdapter != null) {
            if (!mAdapter.isEnabled()) {
                Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                activity.startActivityForResult(intent, REQUEST_ENABLE_BT);
            }
        }
    }


    /**
     * 显示蓝牙列表对话框
     */
    public void showDialog(Activity activity) {

        final Set<BluetoothDevice> bluetoothDeviceSet = getAlreadyPairedBluetoothDeviceList();
        final List<BluetoothDevice> bluetoothDeviceList = new ArrayList<BluetoothDevice>(bluetoothDeviceSet);
        final String[] items = new String[bluetoothDeviceSet.size()];

        for (int i = 0; i < bluetoothDeviceList.size(); i++) {
            items[i] = bluetoothDeviceList.get(i).getName() + " " + bluetoothDeviceList.get(i).getAddress();
        }

        AlertDialog.Builder listDialog = new AlertDialog.Builder(activity);
        listDialog.setTitle("已配对蓝牙列表");
        listDialog.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ToastUtils.showMsg(bluetoothDeviceList.get(which).getName() + " " + bluetoothDeviceList.get(which).getAddress());
            }
        });
        listDialog.show();
    }

    /**
     * 判断蓝牙是否连接
     */
    public boolean isConnection() {
//        int a2dp = adapter.getProfileConnectionState(BluetoothProfile.A2DP);
//        int headset = adapter.getProfileConnectionState(BluetoothProfile.HEADSET);
//        int health = adapter.getProfileConnectionState(BluetoothProfile.HEALTH);
//        return adapter != null && (a2dp == BluetoothAdapter.STATE_CONNECTED ||
//                headset == BluetoothAdapter.STATE_CONNECTED ||
//                health == BluetoothAdapter.STATE_CONNECTED);
        //如果蓝牙状态是未打开的,那么返回未连接
        if (mAdapter.getState() != BluetoothAdapter.STATE_ON) {
            return false;
        }
        return isConnection;
    }


    /**
     * 动态注册广播监听
     *
     * @param activity activity
     * @param receiver 用来监听的广播接收
     * @param listener 用来回调需要处理界面的状态
     */
    public void registerBoradcastReceiver(Activity activity, BluetoothReceiver receiver, final BluetoothListener listener) {
        //蓝牙状态监听,蓝牙关闭,蓝牙开启,蓝牙正在关闭,蓝牙正在开启
        IntentFilter stateChangeFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        //搜索广播
        IntentFilter filterFound = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        //搜索结束
        IntentFilter filterFinished = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        //断开连接
        IntentFilter disConnectedFilter = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        //连接
        IntentFilter connectedFilter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
        //请求配对
        IntentFilter pairingRequestFilter = new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST);
        //配对状态
        IntentFilter pairingStateFilter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        activity.registerReceiver(receiver, stateChangeFilter);
        activity.registerReceiver(receiver, connectedFilter);
        activity.registerReceiver(receiver, disConnectedFilter);
        activity.registerReceiver(receiver, filterFound);
        activity.registerReceiver(receiver, filterFinished);
        activity.registerReceiver(receiver, pairingRequestFilter);
        activity.registerReceiver(receiver, pairingStateFilter);
        receiver.setListener(new BluetoothListener() {
            @Override
            public void bluetoothList(List<BluetoothDevice> deviceList) {
                listener.bluetoothList(deviceList);
            }

            @Override
            public void connection(boolean status) {
                listener.connection(status);
                isConnection = status;
            }
        });
    }

    /**
     * 取消注册广播
     */
    public void unregisterReceiver(Activity activity, BluetoothReceiver receiver) {
        activity.unregisterReceiver(receiver);
    }

    /**
     * 发现蓝牙
     */
    public void doDiscovery() {
        if (mAdapter.isDiscovering()) {
            //如果正在发现,就取消发现
            mAdapter.cancelDiscovery();
        }
        mAdapter.startDiscovery();
    }

    /**
     * @return 是否蓝牙已准备好
     */
    public boolean isAdapterReady() {
        return (mAdapter != null) && (mAdapter.isEnabled());
    }

    public interface MessageCallback {
        void bluttoothMessage(int[] data);
    }
}
